 

package com.junjie.shortlink.admin.common.biz.user;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;

import com.junjie.shortlink.admin.common.convention.exception.ClientException;
import com.junjie.shortlink.admin.common.convention.result.Results;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;

import static com.junjie.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.junjie.shortlink.admin.common.enums.UserErrorCodeEnum.USER_TOKEN_FAIL;

/**
 * 用户信息传输过滤器
 * 过滤器的异常是不会被全局异常处理器拦截到的，要通过response响应回去
 * 这个过滤器是需要通过配置文件去注册的，否则不会生效，因为没有注入容器
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    // 使用了网关后，就不需要单独在网关中进行token验证了
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String username = httpServletRequest.getHeader("username");
        if (StrUtil.isNotBlank(username)) {
            String userId = httpServletRequest.getHeader("userId");
            String realName = httpServletRequest.getHeader("realName");
            UserInfoDTO userInfoDTO = new UserInfoDTO(userId, username, realName);
            UserContext.setUser(userInfoDTO);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }

    // 没有使用网关之前
//    private final StringRedisTemplate stringRedisTemplate;
//
//    // 不需要拦截的接口
//    private static final List<String> IGNORE_URI = Lists.newArrayList(
//            "/api/short-link/admin/v1/user/login",
//            "/api/short-link/admin/v1/user/has-username"
//    );
//
//    @SneakyThrows
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//        String requestURI = httpServletRequest.getRequestURI();
//        if (!IGNORE_URI.contains(requestURI)) {
//            String method = httpServletRequest.getMethod();
//            // 只要不是请求的用户模块的POST请求，就全都拦截
//            if (!(Objects.equals(requestURI, "/api/short-link/admin/v1/user") && Objects.equals(method, "POST"))) {
//                String username = httpServletRequest.getHeader("username");
//                String token = httpServletRequest.getHeader("token");
//                if (!StrUtil.isAllNotBlank(username, token)) {
//                    returnJson((HttpServletResponse) servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
//                    return;
//                }
//                Object userInfoJsonStr;
//                try {
//                    userInfoJsonStr = stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token);
//                    if (userInfoJsonStr == null) {
//                        throw new ClientException(USER_TOKEN_FAIL);
//                    }
//                } catch (Exception ex) {
//                    returnJson((HttpServletResponse) servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
//                    return;
//                }
//                UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
//                UserContext.setUser(userInfoDTO);
//            }
//        }
//        try {
//            filterChain.doFilter(servletRequest, servletResponse);
//        } finally {
//            UserContext.removeUser();
//        }
//    }
//
//    // 响应流设置返回信息
//    private void returnJson(HttpServletResponse response, String json) throws Exception {
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html; charset=utf-8");
//        try (PrintWriter writer = response.getWriter()) {
//            writer.print(json);
//        }
//    }
}